package com.kuang.exam.modules.sys.lesson.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.exam.core.api.dto.PagingReqDTO;
import com.kuang.exam.core.exception.ServiceException;
import com.kuang.exam.core.utils.BeanMapper;
import com.kuang.exam.core.utils.StringUtils;
import com.kuang.exam.modules.qu.dto.export.QuExportDTO;
import com.kuang.exam.modules.sys.lesson.dto.SysLessonDTO;
import com.kuang.exam.modules.sys.lesson.dto.export.LessonExportDTO;
import com.kuang.exam.modules.sys.lesson.entity.SysLesson;
import com.kuang.exam.modules.sys.lesson.entity.SysUserLesson;
import com.kuang.exam.modules.sys.lesson.mapper.SysLessonMapper;
import com.kuang.exam.modules.sys.lesson.service.SysLessonService;
import com.kuang.exam.modules.sys.lesson.service.SysUserLessonService;
import com.kuang.exam.modules.sys.user.entity.SysUser;
import com.kuang.exam.modules.sys.user.service.SysUserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 课程信息业务实现类
 * </p>
 */
@Service
public class SysLessonServiceImpl extends ServiceImpl<SysLessonMapper, SysLesson> implements SysLessonService {

    @Autowired
    private SysUserLessonService userLessonService;

    @Autowired
    private SysUserService userService;

    @Override
    public SysLesson getByName(String name) {
        QueryWrapper<SysLesson> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysLesson::getName, name);
        return this.getOne(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysLessonDTO reqDTO) {

        SysLesson lesson = new SysLesson();
        BeanMapper.copy(reqDTO, lesson);
        // id为空 为添加
        if (StringUtils.isBlank(lesson.getId())) {
            lesson.setId(IdWorker.getIdStr());
        }
        String teachers = null;

        // 更新user_lesson表
        if (!CollectionUtils.isEmpty(reqDTO.getTeacherIds())) {
            // 删除该课程的全部用户（老师）
            QueryWrapper<SysUserLesson> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(SysUserLesson::getLessonId, lesson.getId());
            userLessonService.remove(wrapper);

            List<SysUserLesson> userLessons = new ArrayList<>();
            for (String userId : reqDTO.getTeacherIds()) {
                if (org.springframework.util.StringUtils.isEmpty(teachers)) {
                    teachers = userId;
                } else {
                    teachers += "," + userId;
                }
                SysUserLesson sysUserLesson = new SysUserLesson();
                sysUserLesson.setUserId(userId);
                sysUserLesson.setLessonId(lesson.getId());
                // 老师id是自己本人
                sysUserLesson.setTeacherId(userId);
                userLessons.add(sysUserLesson);
            }
            userLessonService.saveBatch(userLessons);
        }

        // 保存lesson表
        lesson.setTeachers(teachers);
        this.saveOrUpdate(lesson);
    }


    @Override
    public IPage<SysLessonDTO> paging(PagingReqDTO<SysLessonDTO> reqDTO) {

        // 创建分页对象
        Page<SysLesson> query = new Page<>(reqDTO.getCurrent(), reqDTO.getSize());

        // 请求参数
        SysLessonDTO params = reqDTO.getParams();
        //查询条件
        QueryWrapper<SysLesson> wrapper = new QueryWrapper<>();

        if (params != null) {
            if (!StringUtils.isBlank(params.getName())) {
                wrapper.lambda().like(SysLesson::getName, params.getName());
            }

            if (!StringUtils.isBlank(params.getTeachers())) {
                QueryWrapper<SysUser> wrapper1 = new QueryWrapper<>();
                wrapper1.lambda().like(SysUser::getRealName, params.getTeachers());
                SysUser user = userService.getOne(wrapper1);
                if (user != null) {
                    wrapper.lambda().like(SysLesson::getTeachers, user.getId());
                }
            }
        }

        //获得数据
        IPage<SysLesson> page = this.page(query, wrapper);
        //转换结果
        IPage<SysLessonDTO> pageData = JSON.parseObject(JSON.toJSONString(page), new TypeReference<Page<SysLessonDTO>>() {
        });
        //处理名字
        pageData.getRecords().forEach(lessonDTO -> {
            String[] teacherIds = lessonDTO.getTeachers().split(",");
            List<Map<String, String>> teacherList = new ArrayList<>(teacherIds.length);
            lessonDTO.setTeacherIds(Arrays.asList(teacherIds));
            lessonDTO.setTeachers(parseName(lessonDTO.getTeachers(), teacherList));
            lessonDTO.setTeacherList(teacherList);
        });

        return pageData;
    }

    @Override
    public List<LessonExportDTO> listforExport(SysLessonDTO reqDTO) {
        //查询条件
        QueryWrapper<SysLesson> wrapper = new QueryWrapper<>();

        if (reqDTO != null) {
            if (!StringUtils.isBlank(reqDTO.getName())) {
                wrapper.lambda().like(SysLesson::getName, reqDTO.getName());
            }

            if (!StringUtils.isBlank(reqDTO.getTeachers())) {
                QueryWrapper<SysUser> wrapper1 = new QueryWrapper<>();
                wrapper1.lambda().like(SysUser::getRealName, reqDTO.getTeachers());
                SysUser user = userService.getOne(wrapper1);
                if (user != null) {
                    wrapper.lambda().like(SysLesson::getTeachers, user.getId());
                }
            }
        }

        List<SysLesson> lessonList = this.list(wrapper);
        // 将数据库中课程转化未导出课程的结构
        List<LessonExportDTO> exportDTOS = new ArrayList<>(lessonList.size());
        lessonList.forEach(sysLesson -> {
            LessonExportDTO lessonExportDTO = new LessonExportDTO();
            lessonExportDTO.setName(sysLesson.getName());
            lessonExportDTO.setLessonPeriod(String.valueOf(sysLesson.getLessonPeriod()));
            lessonExportDTO.setLessonType(String.valueOf(sysLesson.getLessonType()));
            // 将id 转化为用户名
            String[] teacherIds = sysLesson.getTeachers().split(",");
            String teachers = parseName(sysLesson.getTeachers(), new ArrayList<>());
            lessonExportDTO.setTeachers(Arrays.asList(teachers.split("，")));
            exportDTOS.add(lessonExportDTO);
        });
        return exportDTOS;
    }

    /**
     * 校验Excel
     *
     * @param list
     * @throws Exception
     */
    private Map<Integer, String> checkExcel(List<LessonExportDTO> list) throws ServiceException {
        Map<Integer, String> allTeacherIds = new HashMap<>();
        // 约定第三行开始导入
        int line = 3;
        StringBuilder sb = new StringBuilder();

        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException(1, "您导入的数据似乎是一个空表格！");
        }

        for (LessonExportDTO lessonExport : list) {

            if (StringUtils.isBlank(lessonExport.getName())) {
                sb.append("第").append(line).append("行，课程名称不能为空<br>");
            }

            if (StringUtils.isBlank(lessonExport.getLessonPeriod())) {
                sb.append("第").append(line).append("行，课时不能为空<br>");
            }

            if (StringUtils.isBlank(lessonExport.getLessonType())) {
                sb.append("第").append(line).append("行，课程类型不能为空<br>");
            } else if (!Arrays.asList("1", "0").contains(lessonExport.getLessonType())) {
                sb.append("第").append(line).append("行，课程类型不符合要求<br>");
            }

            // 校验老师账号，并将老师账号转为id
            StringBuilder teacherIds = new StringBuilder();
            if (CollectionUtils.isEmpty(lessonExport.getTeachers())) {
                sb.append("第").append(line).append("行，课程至少需要一个授课老师<br>");
            } else {
                int num = 0;        // 用于判断是否最后一项
                for (String userName : lessonExport.getTeachers()) {
                    SysUser teacher = userService.getByUserName(userName);
                    if (teacher == null) {
                        sb.append("第").append(line).append("行，授课老师\"").append(userName).append("\"账号不存在<br>");
                    } else {
                        if (num == lessonExport.getTeachers().size() - 1) { //最后一项
                            teacherIds.append(teacher.getId());
                        } else {
                            teacherIds.append(teacher.getId()).append(",");
                        }
                    }
                    num++;
                }
            }
            allTeacherIds.put(line, teacherIds.toString());
            line++;
        }
        // 存在错误
        if (!"".equals(sb.toString())) {
            throw new ServiceException(1, sb.toString());
        }
        return allTeacherIds;
    }

    @Override
    public int importExcel(List<LessonExportDTO> dtoList) {
        // 1、先做基本数据校验
        Map<Integer, String> allTeacherIds = checkExcel(dtoList);

        int line = 3;
        // 2、赋值，入库
        for (LessonExportDTO lesson : dtoList) {
            SysLessonDTO sysLessonDTO = new SysLessonDTO();
            sysLessonDTO.setName(lesson.getName());
            sysLessonDTO.setLessonPeriod(Integer.parseInt(lesson.getLessonPeriod()));
            sysLessonDTO.setLessonType(Integer.parseInt(lesson.getLessonType()));
            sysLessonDTO.setTeachers(allTeacherIds.get(line));
            sysLessonDTO.setTeacherIds(Arrays.asList(allTeacherIds.get(line).split(",")));
            this.save(sysLessonDTO);
            line++;
        }
        return 0;
    }


    /**
     * 将id 转化为 名字
     *
     * @param teacherIds
     * @return
     */
    private String parseName(String teacherIds, List<Map<String, String>> teacherList) {
        String[] teachers = teacherIds.split(",");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < teachers.length; i++) {
            SysUser teacher = userService.getById(teachers[i]);
            Map<String, String> teacherMap = new HashMap<>();
            teacherMap.put("id", teachers[i]);
            teacherMap.put("name", teacher.getRealName());
            teacherList.add(teacherMap);
            if (i != teachers.length - 1) {
                stringBuilder.append(teacher.getRealName()).append("，");
            } else {
                stringBuilder.append(teacher.getRealName());
            }
        }
        return stringBuilder.toString();
    }


}
